package com.tester.zc.test002.Volatile;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;


/**
 * 题目3 ：多线程 Volatile 启动两个线程。线程1向容器中新增10个数据。线程2监听容器元素数量，当容器元素数量为5时，线程2输出信息并终止
 *
 * @Author zhoucan
 * @Date 2022/12/11
 */
public class VolatileTest {
    //定义一个集合
    private volatile List<Integer> list = new LinkedList<>();

    //集合中添加数据
    private void add(int i){
        list.add(i);
    }

    //获取集合大小
    private int size(){
        return list.size();
    }

    private static Thread t1 = null;
    private static Thread t2 = null;

    public static void main(String args[]){

        VolatileTest volatileTest = new VolatileTest();

        //线程一 往集合中添加数据
        t1 = new Thread(() ->
        {
            for (int i = 1; i < 10; i++) {
                volatileTest.add(i);
                System.out.println("add Object to Container" + i);
                if (volatileTest.size() == 5) {
                    //唤醒线程t2
                    LockSupport.unpark(t2);
                    //阻塞线程t1
                    LockSupport.park();
                }
            }
        }, "t1");

        //线程二 监控容器数量
        t2 = new Thread(() ->
        {
            //阻塞t2线程
            LockSupport.park();
            //唤醒线程t1
            LockSupport.unpark(t1);
            System.out.println(volatileTest.size());
        }, "t2");

        t1.start();
        t2.start();
    }
}
